package simple.rabbitmq.consumer;

import java.util.Map;

import org.springframework.amqp.AmqpRejectAndDontRequeueException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.SubscribableChannel;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@SpringBootApplication
@EnableBinding(Application.Topic.class)
public class Application {
	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

	@Slf4j
	@Component
	static class Listener {
		@StreamListener(Topic.INPUT)
		public void receive(String payload, @Header(name = "x-death", required = false) Map<?, ?> death) {
			log.info("Received: {}", payload);
			log.info("headeres: {}", death);
			if (death != null && ((Long)death.get("count")) >= 3L) {
	            // giving up - don't send to DLX
				//do something here
				log.info("give up");
	        }else{
	        	throw new AmqpRejectAndDontRequeueException("failed");
	        }
		}
	}

	interface Topic {
		String INPUT = "input";

		@Input(INPUT)
		SubscribableChannel input();
	}
}
